import { request } from "../../utils/util";
let app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    payData: {
      type: Object,
      value: {}
    },
    // 支付类型 venue：场馆支付，goods：商品支付
    type: {
      type: String,
      value: ''
    },
    // 支付类型 order：订单列表
    source: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showSelPay: false,
    payType: 'wx',
    balance: 0, // 余额
  },

  ready() {
    this.getBalance()
    this.setData({
      showSelPay: true
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    close() {
      this.setData({
        showSelPay: false
      })
      this.triggerEvent('close')
    },
    doSelectPay (e) {
      if (this.data.balance < this.data.payData.pay_money) {
        return false
      }
      this.setData({
        payType: e.currentTarget.dataset.type
      })
    },
    pay() {
      if (this.data.payType === 'wx') {
        this.wxPay()
      } else {
        this.balancePay()
      }
    },
    // 余额支付
    balancePay() {
      wx.showLoading({
        title: '加载中..',
        mask: true
      })
      let url = '/api/web/venue/payment'
      if (this.data.type === 'goods') {
        url = '/api/web/shop/payment'
      }
      request({
        url,
        method: 'POST',
        data: this.data.payData,
        success: ({ code, message }) => {
          wx.hideLoading()
          if (code === 200) {
            wx.showToast({
              title: '支付成功！',
              icon: 'success',
              duration: 2000
            })
            setTimeout(() => {
              this.navTo()
            }, 1000)
          } else {
            wx.showToast({
              title: message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },
    // 获取余额
    getBalance() {
      wx.showLoading({
        title: '加载中..',
        mask: true
      })
      request({
        url: '/api/web/personal/recharge',
        success: ({ code, data }) => {
          wx.hideLoading()
          if (code === 200) {
            let balance = 0
            if (data.is_on_account === 0) {
              balance = this.plusBalance(data.recharge_balance, data.give_balance)
            } else {
              balance = this.plusBalance(data.recharge_balance, data.give_balance, data.account_balance)
            }
            this.setData({
              balance: Number(balance)
            })
          }
        }
      })
    },
    // 计算余额
    plusBalance() {
      let num = 0
      for(let i = 0; i < arguments.length; i++) {
        num += this.toInteger(Number(arguments[i]))
      }
      return (num / 100).toFixed(2)
    },
    toInteger(num) {
      let arr = num.toFixed(2).toString().split('.');
      if (arr[1]) {
        return (arr[0] * 100) + Number(arr[1])
      } else {
        return arr[0] * 100
      }
    },
    // 微信支付
    wxPay() {
      wx.showLoading({
        title: '加载中..',
        mask: true
      })
      this.data.payData.type = this.data.type
      this.data.payData.openid = app.globalData.userInfo.openid
      request({
        url: '/api/web/wechat',
        method: 'POST',
        data: this.data.payData,
        success: ({ code, data, message }) => {
          wx.hideLoading()
          if (code === 200) {
            wx.requestPayment({
              timeStamp: `${data.timeStamp}`,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: (result) => {
                if (result.errMsg === 'requestPayment:ok') {
                  wx.showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 2000
                  })
                  setTimeout(() => {
                    this.navTo()
                  }, 1000)
                } else {
                  wx.showToast({
                    title: result.errMsg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              },
              fail (err) {
                console.log(err)
              }
            })
          } else {
            wx.showToast({
              title: message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },
    navTo() {
      if (this.data.type === 'goods') {
        if (this.data.source === 'order') {
          this.triggerEvent('pay-success')
        } else {
          wx.redirectTo({
            url: '/pages/goodsOrder/index'
          })
        }
      } else {
        if (this.data.source === 'order') {
          this.triggerEvent('pay-success')
        } else {
          wx.redirectTo({
            url: '/pages/sportsOrder/index'
          })
        }
      }
    }
  }
})
